package com.project.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.project.bean.NoteBean;
import com.project.bean.UserBean;
import com.project.mapper.INoteMapper;
import com.project.mapper.IUserMapper;
import com.project.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;

@Service
@Transactional
public class UserServiceImpl implements IUserService {
    @Autowired
    private IUserMapper mapper;
    @Autowired
    private INoteMapper noteMapper;


    @Override
    public UserBean login(String code, String pwd) {
        UserBean user=mapper.login(code,pwd);
        if(user!=null){
            //得到当前时分秒
            SimpleDateFormat format=new SimpleDateFormat("HH:mm:ss");
            Date date=new Date();
            format.format(date);
            String str="用户"+user.getName()+"在"+ format.format(date)+"登录客户端";
            noteMapper.add(new NoteBean(str));
        }

        return mapper.login(code,pwd);
    }

    @Override
    public PageInfo<UserBean> findByItem(int pageNO, String name) {
        PageHelper.startPage(pageNO,PAGE_SIZE);
        PageInfo<UserBean> pageInfo = PageInfo.of(mapper.findByItem(name));
        return pageInfo;
    }

    @Override
    public String addUser(UserBean user, int[] roleIdArray) {
        if(mapper.checkUser(user.getCode()) != 0){
            return "no";
        }
        mapper.addUser(user);
        mapper.addUserRole(user.getId(),roleIdArray);

        return "ok";
    }

    @Override
    public void delUser(int id) {
        mapper.delUser(id);
    }

    @Override
    public UserBean findById(int id) {
        UserBean userBean = mapper.findById(id);
        userBean.setUserRole(mapper.findByUserId(id));
        return userBean;
    }

    @Override
    public void update(int id, int[] roleIdArray) {
        mapper.update(id,roleIdArray);
    }

    @Override
    public void updatePwd(int id, String newPwd) {
        mapper.updatePwd(id,newPwd);
    }
}
